var globalCropCallBackFunction ;

function includePhpScript(src) {
    var html_doc = document.getElementsByTagName('head').item(0);
    var js = document.createElement('script');
    js.src = src;
    js.type = 'text/javascript';
    js.defer = true;
    html_doc.appendChild(js);
}

/*
 * Default text - jQuery plugin for html5 dragging files from desktop to browser
 *
 * Author: Weixi Yen
 *
 * Email: [Firstname][Lastname]@gmail.com
 * 
 * Copyright (c) 2010 Resopollution
 * 
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   http://www.github.com/weixiyen/jquery-filedrop
 *
 * Version:  0.1.0
 *
 * Features:
 *      Allows sending of extra parameters with file.
 *      Works with Firefox 3.6+
 *      Future-compliant with HTML5 spec (will work with Webkit browsers and IE9)
 * Usage:
 * 	See README at project homepage
 *
 */

function generateGuid() {
    var S4 = function ()
    {
        return Math.floor(
                Math.random() * 0x10000 /* 65536 */
        ).toString(16);
    };

    return (
            S4() + S4() + "-" +
            S4() + "-" +
            S4() + "-" +
            S4() + "-" +
            S4() + S4() + S4()
    );
}

var uploadMessages = {
		BrowserNotSupported: 'Your browser does not support HTML5 file uploads!',
		TooManyFiles: 'Too many files! Please select 1 at most!',
		FileTooLarge: ' is too large! Please upload files up to 2mb!',
		onlyImages: 'Only images are allowed!',
		firstMessage: 'Drop image here to upload or use the form button.',
		selectImage: 'Select an image !',
		close: 'Close',
		submit: 'Submit',
		IEMessage: 'Click on the "transfer" button'
	};

(function($){

	jQuery.event.props.push("dataTransfer");
	var opts = {},
		default_opts = {
			url: '',
			refresh: 1000,
			paramname: 'userfile',
			maxfiles: 1,
			maxfilesize: 4, // MBs
			data: {},
			drop: empty,
			dragEnter: empty,
			dragOver: empty,
			dragLeave: empty,
			docEnter: empty,
			docOver: empty,
			docLeave: empty,
			beforeEach: empty,
			afterAll: empty,
			rename: empty,
			error: function(err, file, i){alert(err);},
			uploadStarted: empty,
			uploadFinished: empty,
			progressUpdated: empty,
			speedUpdated: empty
		},
		errors = ["BrowserNotSupported", "TooManyFiles", "FileTooLarge"],
		doc_leave_timer,
		stop_loop = false,
		files_count = 0,
		files;

	$.fn.filedrop = function(options) {
		opts = $.extend( {}, default_opts, options );
		
		this.bind('drop', drop).bind('dragenter', dragEnter).bind('dragover', dragOver).bind('dragleave', dragLeave);
		$(document).bind('drop', docDrop).bind('dragenter', docEnter).bind('dragover', docOver).bind('dragleave', docLeave);
	};
     
	function drop(e) {
		opts.drop(e);
		files = e.dataTransfer.files;
		if (files === null || files === undefined) {
			opts.error(errors[0]);
			return false;
		}
		
		files_count = files.length;
		upload();
		e.preventDefault();
		return false;
	}

	function progress(e) {
		if (e.lengthComputable) {
			var percentage = Math.round((e.loaded * 100) / e.total);
			if (this.currentProgress != percentage) {
				
				this.currentProgress = percentage;
				opts.progressUpdated(this.index, this.file, this.currentProgress);
				
				var elapsed = new Date().getTime();
				var diffTime = elapsed - this.currentStart;
				if (diffTime >= opts.refresh) {
					var diffData = e.loaded - this.startData;
					var speed = diffData / diffTime; // KB per second
					opts.speedUpdated(this.index, this.file, speed);
					this.startData = e.loaded;
					this.currentStart = elapsed;
				}
			}
		}
	}
    
	function upload() {
		uploadImage(files, files_count, progress, stop_loop, opts, errors);
	}
    
	function getIndexBySize(size) {
		for (var i=0; i < files_count; i++) {
			if (files[i].size == size) {
				return i;
			}
		}
		
		return undefined;
	}
    
	function rename(name) {
		return opts.rename(name);
	}
	
	function beforeEach(file) {
		return opts.beforeEach(file);
	}
	
	function afterAll() {
		return opts.afterAll();
	}
	
	function dragEnter(e) {
		clearTimeout(doc_leave_timer);
		e.preventDefault();
		opts.dragEnter(e);
	}
	
	function dragOver(e) {
		clearTimeout(doc_leave_timer);
		e.preventDefault();
		opts.docOver(e);
		opts.dragOver(e);
	}
	 
	function dragLeave(e) {
		clearTimeout(doc_leave_timer);
		opts.dragLeave(e);
		e.stopPropagation();
	}
	 
	function docDrop(e) {
		e.preventDefault();
		opts.docLeave(e);
		return false;
	}
	 
	function docEnter(e) {
		clearTimeout(doc_leave_timer);
		e.preventDefault();
		opts.docEnter(e);
		return false;
	}
	 
	function docOver(e) {
		clearTimeout(doc_leave_timer);
		e.preventDefault();
		opts.docOver(e);
		return false;
	}
	 
	function docLeave(e) {
		doc_leave_timer = setTimeout(function(){
			opts.docLeave(e);
		}, 200);
	}
	 
	function empty(){}
	
	try {
		if (XMLHttpRequest.prototype.sendAsBinary) return;
		XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
		    function byteValue(x) {
		        return x.charCodeAt(0) & 0xff;
		    }
		    var ords = Array.prototype.map.call(datastr, byteValue);
		    var ui8a = new Uint8Array(ords);
		    this.send(ui8a.buffer);
		}
	} catch(e) {}
     
})(jQuery);

/*
 * Default text - jQuery plugin for html5 dragging files from desktop to browser
 *
 * Author: Weixi Yen
 *
 * Email: [Firstname][Lastname]@gmail.com
 * 
 * Copyright (c) 2010 Resopollution
 * 
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   http://www.github.com/weixiyen/jquery-filedrop
 *
 * Version:  0.1.0
 *
 * Features:
 *      Allows sending of extra parameters with file.
 *      Works with Firefox 3.6+
 *      Future-compliant with HTML5 spec (will work with Webkit browsers and IE9)
 * Usage:
 * 	See README at project homepage
 *
 */
(function($){

	jQuery.event.props.push("dataTransfer");
	var opts = {},
		default_opts = {
			url: '',
			refresh: 1000,
			paramname: 'userfile',
			maxfiles: 1,
			maxfilesize: 4, // MBs
			data: {},
			beforeEach: empty,
			afterAll: empty,
			rename: empty,
			error: function(err, file, i){alert(err);},
			change: empty,
			uploadStarted: empty,
			uploadFinished: empty,
			progressUpdated: empty,
			speedUpdated: empty
		},
		errors = ["BrowserNotSupported", "TooManyFiles", "FileTooLarge", "IEMessage"],
		doc_leave_timer,
		stop_loop = false,
		files_count = 0,
		files,
		inputId;

	$.fn.fileselect = function(options) {
		opts = $.extend( {}, default_opts, options );
		
		this.bind('change', change);
		inputId = this.attr('id');
	};
     
	function change(e) {
		var fileInput = document.getElementById(inputId);
		if(fileInput.value !== ''){
			opts.change(e);
			files = fileInput.files;
			
			if (files === null || files === undefined || !window.FileReader) {
				opts.error(errors[3]);
				
				var oldName = $(fileInput).attr('name');
				var guid = generateGuid();
			
				var dbSubmit = $('#dropbox_inputDivFormSubmit');
				if (dbSubmit.length == 0) {
					var dbPrevDiv = $('#image-uploader-container');
					dbPrevDiv.append('<iframe id="uploadIframe" style="display: none;" name="uploadIframe"></iframe>');
					$('#dropbox_inputDivForm').append('<input id="dropbox_inputDivFormSubmit" type="submit" value="Transférer" />');
				}
				$(fileInput).attr('name', 'pic');
				$('#dropbox_inputDivForm').attr('action', opts.url+'?ie=true');
				$('#dropbox_file_id').attr('value', guid);
				
				$('#dropbox_inputDivFormSubmit').click(function() {
					
					createImage(null, $("#dropbox"), true);
					
					$('#uploadIframe').unbind();
					$('#uploadIframe').load(function(){
						includePhpScript(opts.url+'?ie=true&id='+guid);
					});
				});
			} else {
				files_count = files.length;
				upload();
			}
		}
		e.preventDefault();
		return false;
	}
	
	function progress(e) {
		if (e.lengthComputable) {
			var percentage = Math.round((e.loaded * 100) / e.total);
			if (this.currentProgress != percentage) {
				
				this.currentProgress = percentage;
				opts.progressUpdated(this.index, this.file, this.currentProgress);
				
				var elapsed = new Date().getTime();
				var diffTime = elapsed - this.currentStart;
				if (diffTime >= opts.refresh) {
					var diffData = e.loaded - this.startData;
					var speed = diffData / diffTime; // KB per second
					opts.speedUpdated(this.index, this.file, speed);
					this.startData = e.loaded;
					this.currentStart = elapsed;
				}
			}
		}
	}
    
    
    
	function upload() {
		uploadImage(files, files_count, progress, stop_loop, opts, errors);
	}
    
	function getIndexBySize(size) {
		for (var i=0; i < files_count; i++) {
			if (files[i].size == size) {
				return i;
			}
		}
		
		return undefined;
	}
    
	function rename(name) {
		return opts.rename(name);
	}
	
	function beforeEach(file) {
		return opts.beforeEach(file);
	}
	
	function afterAll() {
		return opts.afterAll();
	}
	 
	function empty(){}
	
	try {
		if (XMLHttpRequest.prototype.sendAsBinary) return;
		XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
		    function byteValue(x) {
		        return x.charCodeAt(0) & 0xff;
		    }
		    var ords = Array.prototype.map.call(datastr, byteValue);
		    var ui8a = new Uint8Array(ords);
		    this.send(ui8a.buffer);
		}
	} catch(e) {}
     
})(jQuery);

var jcrop_api=null;
var jcrop_image=null;

function uploadImage(files, files_count, progress, stop_loop, opts, errors) {
	stop_loop = false;
	if (!files) {
		opts.error(errors[0]);
		return false;
	}
	var filesDone = 0,
		filesRejected = 0;
	
	if (files_count > opts.maxfiles) {
	    opts.error(errors[1]);
	    return false;
	}

	for (var i=0; i<files_count; i++) {
		if (stop_loop) return false;
		try {
			if (opts.beforeEach(files[i]) != false) {
				if (i === files_count) return;
				var reader = new FileReader(),
					max_file_size = 1048576 * opts.maxfilesize;
					
				reader.index = i;
				if (files[i].size > max_file_size) {
					opts.error(errors[2], files[i], i);
					filesRejected++;
					continue;
				}
				
				reader.onloadend = send;
				reader.readAsBinaryString(files[i]);
			} else {
				filesRejected++;
			}
		} catch(err) {
			opts.error(errors[0]);
			return false;
		}
	}
    
	function send(e) {
		// Sometimes the index is not attached to the
		// event object. Find it by size. Hack for sure.
		if (e.target.index == undefined) {
			e.target.index = getIndexBySize(e.total);
		}
		
		var xhr = new XMLHttpRequest(),
			upload = xhr.upload,
			file = files[e.target.index],
			index = e.target.index,
			start_time = new Date().getTime(),
			boundary = '------multipartformboundary' + (new Date).getTime(),
			builder;
			
		newName = opts.rename(file.name);
		if (typeof newName === "string") {
			builder = getBuilder(newName, e.target.result, boundary, opts);
		} else {
			builder = getBuilder(file.name, e.target.result, boundary, opts);
		}
		
		upload.index = index;
		upload.file = file;
		upload.downloadStartTime = start_time;
		upload.currentStart = start_time;
		upload.currentProgress = 0;
		upload.startData = 0;
		upload.addEventListener("progress", progress, false);
		
		xhr.open("POST", opts.url, true);
		xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' 
		    + boundary);
		    
		xhr.sendAsBinary(builder);  
		
		opts.uploadStarted(index, file, files_count);  
		
		xhr.ontimeout = function() {
			alert('error during upload : timeout');
		};
		xhr.onerror = function() {
			alert('error during upload');
		};
		xhr.onabort = function() {
			alert('upload aborted');
		};
		
		xhr.onload = function() { 
		    if (xhr.responseText) {
		    	var now = new Date().getTime(),
			    timeDiff = now - start_time,
			    result = opts.uploadFinished(index, file, jQuery.parseJSON(xhr.responseText), timeDiff);
				filesDone++;
				if (filesDone == files_count - filesRejected) {
					opts.afterAll();
				}
				if (result === false) {
					stop_loop = true;
					alert('error during upload');
				}
				
		    } else {
		    	alert('error sending image');
		    }
		};
	}
}

function getBuilder(filename, filedata, boundary, opts) {
	var dashdash = '--',
		crlf = '\r\n',
		builder = '';

	$.each(opts.data, function(i, val) {
    	if (typeof val === 'function') val = val();
		builder += dashdash;
		builder += boundary;
		builder += crlf;
		builder += 'Content-Disposition: form-data; name="'+i+'"';
		builder += crlf;
		builder += crlf;
		builder += val;
		builder += crlf;
	});
	
	builder += dashdash;
	builder += boundary;
	builder += crlf;
	builder += 'Content-Disposition: form-data; name="'+opts.paramname+'"';
	builder += '; filename="' + filename + '"';
	builder += crlf;
	
	builder += 'Content-Type: application/octet-stream';
	builder += crlf;
	builder += crlf; 
	
	builder += filedata;
	builder += crlf;
    
	builder += dashdash;
	builder += boundary;
	builder += dashdash;
	builder += crlf;
	return builder;
}

function createImage(file, dropbox, ie){

	if (typeof ie == 'undefined') {
		ie = false;
	}
	
	jcrop_image.status = false;
	jcrop_image.ie = ie;
	
	var marginTop = Math.round((dropbox.height()-100)/2);
	var marginLeft = Math.round((dropbox.width()-100)/2);
	
	var imagePreviewtemplate = '<div class="previewImage">'+
									'<span class="imageHolder">'+
										'<img src="./Images/AlloMedia/ajax-loader.gif" style="width:100px;height:100px;margin:'+marginLeft+'px;margin-top:'+marginTop+'px;"/>'+
										'<span class="uploaded"></span>'+
									'</span>'+
									'<div class="progressHolder">'+
										'<div class="progress"></div>'+
									'</div>'+
								'</div>'; 
	
	var preview = $(imagePreviewtemplate);
	dropbox.empty();
	preview.appendTo(dropbox);
	var image = $('img', preview);
		
	// Associating a preview container
	// with the file, using jQuery's $.data():
	if (file != null) {
		$.data(file,preview);
	}
}

function showImageUploadMessage(dropbox, msg){
	dropbox.empty();
	var height = dropbox.height();
	var message = $('<span class="message">'+msg+'</span>');
	message.css('padding-top', Math.round(height/2)-10);
	message.appendTo(dropbox);
}

function resetImage(dropboxId) {
	var image = $('img', $('#'+dropboxId)).attr('src', '');
}

function uploadFinished(i,file,response, dropbox) {
	if(response.status == true) {
		
		var image = $('img', dropbox);
		image.attr('src',response.file);
		
		var realPath = response.path;
		
		var containerWidth = dropbox.width();
		var containerHeight = dropbox.height();
		
		var ratio = containerWidth/containerHeight;
		
		var myImage = new Image();
		myImage.src = image.attr('src');
		myImage.onload = function() {
			$('.cropMessage').css('display', 'block');
			$('.cropMessage').show();
			
			var imageWidth = myImage.width ;
			var imageHeight = myImage.height;
			image.width(imageWidth); image.attr('width', imageWidth);
			image.height(imageHeight); image.attr('height', imageHeight);
			
			jcrop_image.path = image.attr('src');
			jcrop_image.realPath = realPath;
			jcrop_image.originalWidth = imageWidth;
			jcrop_image.originalHeight = imageHeight;
			
			if (jcrop_api != null) {
				jcrop_api.destroy();
			}
			
			var imageRatio = imageWidth/imageHeight;
			var x1=0, y1=0, x2=imageWidth, y2=imageHeight;
			
			var newHeight=imageHeight, newWidth=imageWidth;
			
			if(imageRatio!=ratio) {
				if (imageRatio>ratio) {
					x1 = Math.round((imageWidth - (imageHeight*ratio))/2);
					x2 = imageWidth-x1;
					if(imageWidth>containerWidth) {
						newWidth = containerWidth;
						newHeight = Math.round(containerWidth/imageRatio);
					}
				} else {
					y1 = Math.round((imageHeight - (imageWidth/ratio))/2);
					y2 = imageHeight-y1;
					if(imageHeight>containerHeight) {
						newWidth = Math.round(containerHeight*imageRatio);
						newHeight = containerHeight;
					}
				}
			} else {
				newWidth = containerWidth;
				newHeight = containerHeight;
			}
			$('.imageHolder', dropbox).css('padding-left', Math.round((containerWidth-newWidth)/2));
			$('.imageHolder', dropbox).css('padding-top', Math.round((containerHeight-newHeight)/2));
			
			jcrop_image.x1 = x1;
			jcrop_image.y1 = y1;
			jcrop_image.x2 = x2;
			jcrop_image.y2 = y2;
			jcrop_image.width = x2-x1;
			jcrop_image.height = y2-y1;
			jcrop_image.status = true;
			
			image.Jcrop({aspectRatio: ratio, boxWidth: containerWidth, boxHeight: containerHeight, setSelect: [x1,y1,x2,y2], onRelease:function(){jcrop_image.status = false;}, onSelect:getNewSize},function(){
			  jcrop_api = this;
			});
			
		}
		
		$('.message', dropbox).hide();
		
	} else {
		showImageUploadMessage(dropbox, response.message);
	}
	
	$('.progressHolder', dropbox).hide();
}

function getNewSize(c) {
	jcrop_image.x1 = c.x;
	jcrop_image.y1 = c.y;
	jcrop_image.x2 = c.x2;
	jcrop_image.y2 = c.y2;
	jcrop_image.width = c.w;
	jcrop_image.height = c.h;
	jcrop_image.status = true;
}

function uploadError(err, file, dropbox) {
	switch(err) {
		case 'BrowserNotSupported':
			showImageUploadMessage(dropbox, uploadMessages.BrowserNotSupported);
			break;
		case 'TooManyFiles':
			showImageUploadMessage(dropbox, uploadMessages.TooManyFiles);
			break;
		case 'FileTooLarge':
			showImageUploadMessage(dropbox, file.name+uploadMessages.FileTooLarge);
			break;
		case 'IEMessage':
			showImageUploadMessage(dropbox, uploadMessages.IEMessage);
			break;
		default:
			break;
	}
}

function checkFileType(file) {
	if(!file.type.match(/^image\//)){
		alert(uploadMessages.onlyImages);
		
		// Returning false will cause the
		// file to be rejected
		return false;
	}
}

function resetDropbox(dropboxId, uploadUrl, maxFilesNb, paramName, width, height, messageStyle) {
	
	jcrop_image = new Object();
	
	$('.cropMessage').css('display', 'none');
	$('.cropMessage').hide();
	
	var dropbox = $('#'+dropboxId) ;
	dropbox.width(width);
	dropbox.height(height);
	
	var imageInput = $('#'+dropboxId+'_input');
	if(imageInput.length == 0){
		var inputText = '<div id="'+dropboxId+'_inputDiv">'+
				'<form target="uploadIframe" action="#" method="POST" enctype="multipart/form-data" id="dropbox_inputDivForm">'+
					'<input type="file" name="'+dropboxId+'_input" id="'+dropboxId+'_input" />'+
					'<input type="hidden" name="id" id="dropbox_file_id" />'+
				'</form>';
			'</div>';
		
		var imageInputDiv = $(inputText);
		dropbox.parent().append(imageInputDiv);
		
		imageInput = $('#'+dropboxId+'_input');
		
		imageInput.fileselect({
			// The name of the $_FILES entry:
			paramname:paramName,
			
			maxfiles: maxFilesNb,
	    	maxfilesize: 4,
			url: uploadUrl,
			
			uploadFinished:function(i,file,response){
				uploadFinished(i,file,response, dropbox);
			},
			
	    	error: function(err, file) {
	    		uploadError(err, file, dropbox);
			},
			
			// Called before each upload is started
			beforeEach: function(file){
				return checkFileType(file);
			},
			
			uploadStarted:function(i, file, len){
				createImage(file, dropbox);
			},
			
			progressUpdated: function(i, file, progress) {
				$.data(file).find('.progress').width(progress);
			}
		});
	}
	
	imageInput.val('');
	
	var previewImage = $('.previewImage', dropbox);
	if(previewImage.length == 0) {
		dropbox.filedrop({
			// The name of the $_FILES entry:
			paramname:paramName,
			
			maxfiles: maxFilesNb,
	    	maxfilesize: 4,
			url: uploadUrl,
			
			uploadFinished:function(i,file,response){
				uploadFinished(i,file,response, dropbox);
			},
			
	    	error: function(err, file) {
	    		uploadError(err, file, dropbox);
			},
			
			// Called before each upload is started
			beforeEach: function(file){
				return checkFileType(file);
			},
			
			uploadStarted:function(i, file, len){
				createImage(file, dropbox);
			},
			
			progressUpdated: function(i, file, progress) {
				$.data(file).find('.progress').width(progress);
				if (progress == 100) {
					imageInput.attr('value', '');
				}
			}
	    	 
		});
	}
	
	dropbox.empty();
	
	if (messageStyle==null) {
		messageStyle='';
	}
	var message = $('<span class="message '+messageStyle+'">'+uploadMessages.firstMessage+'</span>');
	if (messageStyle=='') {
		message.css('padding-top', Math.round(height/2)-10);
	}
	message.appendTo(dropbox);
	
	return dropbox;
}

function createFileUploader(dropboxId, uploadUrl, maxFilesNb, paramName, width, height){
	resetDropbox(dropboxId, uploadUrl, maxFilesNb, paramName, width, height);
}

function getJcropImage() {
	return jcrop_image;
}

function prepareImageLoader(img) {
	var imgWidth = img.width();
    var imgHeight = img.height();
    img.parent().width(imgWidth);
    img.parent().height(imgHeight);

    img.width(24);
    img.height(24);
    img.css('margin-left', Math.round((imgWidth-24)/2));
    img.css('margin-top', Math.round((imgHeight-24)/2));
    img.css('position', 'absolute');
    img.attr('src', './Images/Default/loading.gif');
}

function hideImageLoader(img) {
	img.css('margin-left', 0).css('margin-top', 0);
	img.css('position', 'relative');
    img.width(img.parent().width());
    img.height(img.parent().height());
}

function cropImage(cropUrl, preCropCallBack, postCropCallBack){
	var jcropOptions = getJcropImage();
	if(jcropOptions == null || jcropOptions == undefined || !jcropOptions.status) {
		alert(uploadMessages.selectImage);
		jcropOptions = null;
	}
	
	if (jcropOptions != null) {
		
		jcropOptions = preCropCallBack(jcropOptions);
		
		var cropForm = $('.uploadImage', $('#boxshadow-image'));
		
    	var cropFormFields = $('#cropFormFields');
    	if (cropFormFields.length == 0) {
    		cropForm.append('<div style="display:none" id="cropFormFields"></div>');
    		cropFormFields = $('#cropFormFields');
        }
    	cropFormFields.empty();
    	
    	for (var cropParam in jcropOptions) {
    		var cropParamValue = jcropOptions[cropParam];
    		cropFormFields.append('<input type="hidden" name="'+cropParam+'" value="'+cropParamValue+'" />');
    	}
    	
    	globalCropCallBackFunction = postCropCallBack;
    	
    	var cropParams = cropForm.serialize();
    	var realCropUrl = cropUrl+'&'+cropParams;
    	
    	includePhpScript(realCropUrl);
    	closeImageSelecter(null);
    }
	
	return false;
}

function closeImageSelecter(value) {
	$('#boxshadow-image').hide();
	$('#boxshadow-image-background').hide();
	
	if(value != null) {
		$("#croppedImageField").val(value.path);
	}
}

function showImageSelecter(cropUrl, preCropCallBack, postCropCallBack) {
	$('#boxshadow-image').show();
	$('#boxshadow-image-background').show();
	
	$('.closeImage', $('#boxshadow-image')).unbind();
	$('.closeImage', $('#boxshadow-image')).click(function(){
		closeImageSelecter(null);
	});
	
	$('.uploadImage', $('#boxshadow-image')).unbind();
	$('.uploadImage', $('#boxshadow-image')).submit(function(){
		return cropImage(cropUrl, preCropCallBack, postCropCallBack);
	});
	
	centerImageSelecter($('#boxshadow-image'),$('#boxshadow-image-background'));
}

function centerImageSelecter(boxShadow, boxShadowBackground) {
	boxShadow.css('top', ($(window).height()-boxShadow.height())/2);
	boxShadow.css('left', ($(window).width()-boxShadow.width())/2);
	
	boxShadowBackground.width($(document).width());
	boxShadowBackground.height($(document).height());
}

function addImageSelecter(dropboxId) {
	
	var boxShadow = $('#boxshadow-image');
	var boxShadowBackground  = $('#boxshadow-image-background');
	
	if(boxShadow.length == 0) {
		$('body').append('<div id="boxshadow-image"></div>');
		
		boxShadow = $('#boxshadow-image');
		
		boxShadowBackground = $('<div id="boxshadow-image-background"></div>');
		boxShadowBackground.insertBefore(boxShadow);
		
		boxShadowBackground = $('#boxshadow-image-background');
		boxShadowBackground.hide();
		boxShadowBackground.css('position', 'absolute');
		boxShadowBackground.css('top', '0');
		boxShadowBackground.css('left', '0');
		boxShadowBackground.css('background', '#000000');
		boxShadowBackground.css('opacity', '0.6');
		
    	boxShadow.append('<div id="image-uploader-container"><div id="'+dropboxId+'" class="dropbox"></div></div>');
    	boxShadow.append('<p class="cropMessage" style="display:none;">Sélectionnez la zone de l\'image à cadrer puis appuyez sur envoyer.</p>');
    	boxShadow.append('<form action="#" class="uploadImage"><input type="hidden" id="croppedImageField" name="croppedImage" value="" /><input type="button" class="closeImage" value="'+uploadMessages.close+'" /><input type="submit" value="'+uploadMessages.submit+'" /></form>');
    	boxShadow.css('position', 'fixed');
    	boxShadow.css('z-index', '9999');
    	
    	$(window).resize(function(){
    		centerImageSelecter(boxShadow, boxShadowBackground);
        });
    	
    	boxShadowBackground.click(function(){
    		closeImageSelecter(null);
    	});
	}
	boxShadowBackground.hide();
	boxShadow.hide();
}	

function addImageSelecterCallback(linkIdentifier, dropboxId, uploadUrl, maxFilesNb, paramName, width, height, cropUrl, preCropCallBack, postCropCallBack, messageStyle) {
	$(linkIdentifier).click(function (){		      		
		resetDropbox(dropboxId, uploadUrl, maxFilesNb, paramName, width, height, messageStyle);
		showImageSelecter(cropUrl, preCropCallBack, postCropCallBack);
		return false;
	});
}